#!/bin/bash

# 定义颜色变量
GREEN="\033[0;32m"
RED="\033[0;31m"
NC="\033[0m # No Color"

# 执行idf.py build
idf.py build

# 检查构建是否成功
if [ $? -eq 0 ]; then
    echo -e "${GREEN}Build succeeded!${NC}"

    # 从CMakeLists.txt文件中提取版本号
    VERSION=$(grep -oP 'set\(PROJECT_VER "\K[^"]+' CMakeLists.txt)

    # 检查是否提取到版本号
    if [ -z "$VERSION" ]; then
        echo -e "${RED}Version not found in CMakeLists.txt!${NC}"
        exit 1
    fi

    # 重新格式化版本号为v1_0_0的形式
    FORMATTED_VERSION=$(echo "$VERSION" | tr '.' '_')

    # 定义要拷贝的文件路径列表
    FILES_TO_COPY=(
        "build/bootloader/bootloader.bin"
        "build/partition_table/partition-table.bin"
        "build/smart-socket.bin"
        "build/ota_data_initial.bin"
    )

    # 确保firmware目录存在
    mkdir -p firmware

    # 遍历文件列表并拷贝到firmware目录
    for file in "${FILES_TO_COPY[@]}"; do
        if [ -f "$file" ]; then
            # 如果是smart-socket.bin文件，则进行重命名
            if [[ "$file" == "build/smart-socket.bin" ]]; then
                DEST="firmware/smart-socket_v${FORMATTED_VERSION}.bin"
                cp "$file" "$DEST"
                echo "Copied $file to $DEST."
            else
                cp "$file" firmware/
                echo "Copied $file to firmware directory."
            fi
        else
            echo -e "${RED}File $file not found.${NC}"
        fi
    done
else
    echo -e "${RED}Build failed!${NC}"
fi
